package com.yl.chainStore.payrule.item.service

import com.yl.chainStore.entity.pay.PayCustomerOrder
import com.yl.chainStore.entity.pay.PayCustomerOrderItemDiscountRuleLog
import com.yl.chainStore.payrule.common.DiscountComputeOrderResultVo
import com.yl.chainStore.payrule.item.ItemRuleService
import com.yl.chainStore.payrule.item.ItemRuleTypeEnum
import com.yl.chainStore.payrule.item.entity.BuyAndDiscountRule
import com.yl.chainStore.services.IWebCompanyDeptService
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service

@Service
class BuyAndSendRuleServiceImpl : ItemRuleService() {

	@Autowired
	private lateinit var iWebCompanyDeptService: IWebCompanyDeptService

	private val ruleType = ItemRuleTypeEnum.BUY_AND_DISCOUNT_RULE

	/**
	 * 处理方式
	 * 买n 减多少钱
	 */
	override fun computeOrder(order: PayCustomerOrder): DiscountComputeOrderResultVo {
		val ruleList =
			iWebCompanyDeptService.getNowOpenItemDiscountRuleList(getContext().subCompanyId, ruleType)
		if(order.details != null && order.details!!.isNotEmpty()){
			for(itemRule in ruleList){
				val rule = itemRule.getOtherContentObj() as BuyAndDiscountRule
				for(detail in order.details!!){
					if(detail.gift == 1){
						continue
					}
					if(detail.itemId == rule.buyItemId){
						var discountMoney = rule.disCountMoney
						val realMoney = detail.realMoney
						if(detail.realMoney < rule.disCountMoney){
							detail.realMoney = 0
							discountMoney = realMoney
						}else{
							detail.realMoney = detail.realMoney - rule.disCountMoney
							detail.realPrice = detail.realMoney.div(detail.number)
							order.originalPrice = order.originalPrice - discountMoney
						}
						order.addPayCustomerOrderItemDiscountRuleLog(
							PayCustomerOrderItemDiscountRuleLog(
								id = 0L,
								orderId = order.id,
								detailId = detail.id,
								content = itemRule.title,
								ruleType = ruleType,
								ruleId = itemRule.id,
								discountMoney = discountMoney
							)
						)
						break
					}

				}
			}
		}
		return DiscountComputeOrderResultVo(returnSuccess(),order)
	}
}

